package com.sy.springboottest.action.proxy;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Arrays;

import com.sy.springboottest.pojo.QueryPojo;
import com.sy.springboottest.pojo.QueryProtoOuterClass;
import com.sy.springboottest.pojo.QueryProtoOuterClass.QueryProto;
import com.sy.springboottest.pojo.ResultProtoOuterClass.ResultProto;
import com.sy.springboottest.pojo.ResultPojo;
import com.sy.springboottest.pojo.ResultProtoOuterClass;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class ProxyUtil implements MethodInterceptor {
	
	public Socket getSocket() {
		Socket socket =  null;
		try {
			socket = new Socket("127.0.0.1",8080);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return socket;
	}

	@Override
	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		System.out.println("Before:" + method);
		//建立链接
		Socket socket = getSocket();
		//对象输出
		OutputStream outputStream = socket.getOutputStream();
//        ObjectOutputStream oos = new ObjectOutputStream(outputStream);
//        
//        oos.writeObject(args[0]);
//        oos.flush();
//        outputStream.flush();
//        
//        InputStream inputStream = socket.getInputStream();
//        ObjectInputStream objIs = new ObjectInputStream(inputStream);
//        ResultPojo res = (ResultPojo) objIs.readObject();
//		System.out.println(res.getSum());
		
		QueryProtoOuterClass.QueryProto qp = QueryProtoOuterClass.QueryProto.newBuilder().setFirst(1).setSecond(2).build();
		qp.writeTo(outputStream);
		socket.shutdownOutput();
		ResultProtoOuterClass.ResultProto parseFrom = ResultProtoOuterClass.ResultProto.parseFrom(socket.getInputStream());
		System.out.println(parseFrom.getSum());
		System.out.println("After:" + method);
		return null;
	}
}
